package cn.zifangsky.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//这里面的配置代码都是一些程式化的，按照下面的配置就可以支持http请求
@Configuration
//只有当server.ssl.key-store存在才说明要开启https
@ConditionalOnProperty(name="server.ssl.key-store",matchIfMissing = false)
public class TomcatConfig {

    @Value("${server.port}")
    private String httpsPort;

    @Value("${myconfig.server.http.port}")
    private String httpPort;

    @Bean
    TomcatServletWebServerFactory tomcatServletWebServerFactory(){
        TomcatServletWebServerFactory tomcatServletWebServerFactory = new TomcatServletWebServerFactory(){
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection securityCollection = new SecurityCollection();
                securityCollection.addPattern("/*");
                securityConstraint.addCollection(securityCollection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcatServletWebServerFactory.addAdditionalTomcatConnectors(myConnector());
        return tomcatServletWebServerFactory;
    }

//    下面配置：当使用http协议的8081端口请求数据会转发到8080端口
    private Connector myConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(Integer.valueOf(httpPort));
        connector.setSecure(false);
        connector.setRedirectPort(Integer.valueOf(httpsPort));
        return connector;
    }
}
